from django import forms
from django.core.exceptions import ValidationError

from web.forms.bootstrap import BootStrapForm
from web import models

from utils.tencent.cos import check_file


class FolderModelFrom(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.FileRepository
        fields = ['name', ]

    def __init__(self, request, parent_object, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_object = parent_object

    def clean_name(self):
        """ 项目名字校验 """
        name = self.cleaned_data['name']
        creator = self.request.bug_platform.user  # 拿到创建者
        # 1，判断当前用户 当前文件下的此文件是否已创建此文件 (是否存在
        # 在这需要判断创建者的项目名不能重复，当项目创建者不同时，项目名是可以重复的
        queryset = models.FileRepository.objects.filter(file_type=2, name=name, project=self.request.bug_platform.project)
        if self.parent_object:
            # models.FileRepository.objects.filter(file_type=2, name=name, project=self.request.bug_platform.project, parent=self.parent_object).exists()
            exists = queryset.filter(parent=self.parent_object).exists()
        else:
            # models.FileRepository.objects.filter(file_type=2, name=name, project=self.request.bug_platform.project, parent__isnull=True).exists()
            exists = queryset.filter(parent__isnull=True).exists()

        if exists:
            raise ValidationError('在此文件夹中有相同的文件名')
        return name


class FileModelForm(forms.ModelForm):
    etag = forms.CharField(label='ETag')

    class Meta:
        model = models.FileRepository
        exclude = ['project', 'file_type', 'update_user', 'update_datetime']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_file_path(self):
        return f'https://{self.cleaned_data["file_path"]}'

    def clean(self):
        etag = self.cleaned_data['etag']
        key = self.cleaned_data['key']
        size = self.cleaned_data['file_size']

        if not etag or not key:
            return self.cleaned_data
        # 和cos校验etag是否相同
        from qcloud_cos.cos_exception import CosServiceError
        try:
            result = check_file(self.request.bug_platform.project.bucket, self.request.bug_platform.project.region, key)
        except CosServiceError as e:
            self.add_error('key', '文件不存在')
            return self.cleaned_data

        cos_etag = result.get('ETag')
        if etag != cos_etag:
            self.add_error('etag', 'ETag错误')

        cos_Length = result.get('Content-Length')
        if int(cos_Length) != size:
            self.add_error('size', '文件大小错误')

        return self.cleaned_data